#include <defs.h>

.extern start_kernel
.extern sbi_ecall
.extern task_init
.extern early_pgtbl

.macro PRINT str
    la a0, \str
    mv a1, x0
    mv a2, x0
    mv a3, x0
    mv a4, x0
    mv a5, x0
    li a6, 0
    li a7, 1
    ecall
.endm

.section .text.init
.globl _start
_start:
    la sp, boot_stack_top

    call setup_vm
    call relocate
 # ------------------
    PRINT 'B'

    call mm_init

    PRINT 'C'
    call setup_vm_final
    PRINT 'R'
    call task_init


    # set stvec = _traps
    la t0, _traps
    csrw stvec, t0

# ------------------

    # set sie[STIE] = 1
    csrr t0, sie
    li t1, 0x20
    or t0, t0, t1
    csrw sie, t0

# ------------------
# 设置第一次时钟中断
    # set mtimecmp = mtime + 10000000
    rdtime t0
    li t1, 10000000
    add t0, t0, t1
    # call opensbi ecall to set mtimecmp to t0
    mv a0, t0
    mv a1, x0
    mv a2, x0
    mv a3, x0
    mv a4, x0
    mv a5, x0
    li a6, 0
    li a7, 0
    ecall

# ------------------
# sstatus: 0:UIE 1:SIE, 2:reserved, 3:MIE, 4:UPIE, 5:SPIE, 6:reserved, 7:MPIE, 8:SPP
    # li a6, 0x00
    # li a7, 0x01
    # li a0, 'B'
    # ecall




    # ; li t0, 0x80200578
    

    # set sstatus[SIE] = 1
    # csrr t0, sstatus
    # li t1, 0x2          # 0x2 = 0b10 SIE
    # or t0, t0, t1
    # csrw sstatus, t1
# ------------------


    # ------------------
    # - lab1 code here -
    # ------------------
    jal x0, start_kernel


relocate:
    # set ra = ra + PA2VA_OFFSET
    li t2, PA2VA_OFFSET
    add ra, ra, t2
    # set sp = sp + PA2VA_OFFSET (If you have set the sp before)
    add sp, sp, t2
   
    ###################### 
    #   YOUR CODE HERE   #
    ######################

    # set satp with early_pgtbl
    add t0, x0, x0

    li t0, 0x8000000000000000
    la t1, early_pgtbl
    # sub t1, t1, t2
    srli t1, t1, 12
    or t0, t0, t1
    
    csrw satp, t0
    
    ###################### 
    #   YOUR CODE HERE   #
    ######################
    
    # flush tlb
    sfence.vma zero, zero
    PRINT 'A'
    # change ra to num char, and print it
    
    ret


    .section .bss.stack
    .globl boot_stack

boot_stack:
    .space 0x1000 # <-- change to your stack size

    .globl boot_stack_top
boot_stack_top: